package com.youlu.campus.web.config.filter;

import com.youlu.campus.service.system.SystemIpLimitService;
import com.youlu.campus.web.config.filter.utils.IpUtils;
import com.youlu.campus.web.config.filter.utils.ResponseUtils;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ip黑名单限制 过滤器
 *
 * @Description: IpBlackListFilter
 * @Date 2025/7/10
 * @module IpBlackListFilter
 * @author: su
 */
@Slf4j
public class IpLimitFilter extends OncePerRequestFilter {

    private final SystemIpLimitService systemIpLimitService;

    public IpLimitFilter(SystemIpLimitService systemIpLimitService) {
        this.systemIpLimitService = systemIpLimitService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取ip
        String requestIp = IpUtils.getRequestIpAddress(request);
        if (StringUtils.isBlank(requestIp)) {
            filterChain.doFilter(request, response); //放行
            return;
        }
        log.info("requestIp: {}", requestIp);
        boolean result = systemIpLimitService.existIp(requestIp);
        if (result) {
            log.error("非法访问IP: {}", requestIp);
            ResponseUtils.writeOutJson(response, QResult.fail("非法访问,请联系管理员!"));
            return;
        }
        filterChain.doFilter(request, response); //放行
    }
}
